"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : autocommit
Case Name   : 关闭自动提交，执行语句，重启数据库，未提交的数据自动回退
Create At   : 2023/01/17
@zou_jialiang0501162244
Description :
    1、session1关闭自动提交，建表，提交，表中插入数据，查询表数据，不提交
    2、新开session2重启数据库
    3、查询表数据
    4、清理环境
Expect      :
    1、执行成功，两条数据
    2、重启数据库成功
    3、查询表存在，表中无数据
    4、成功
History     :
"""

import os
import time
import unittest

from testcase.utils.Logger import Logger
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.ComThread import ComThread


class TestAutocommit(unittest.TestCase):

    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.pri_sh = CommonSH('PrimaryDbUser')
        self.constant = Constant()
        self.tb_name = 't_autocommit_0015'
        self.db_name = 'db_autocommit_0015'
        self.log.info("-----预置兼容B库-----")
        preset_db = f"drop database if exists {self.db_name};" \
                    f"create database {self.db_name} dbcompatibility 'B';"
        preset_db_res = self.pri_sh.execut_db_sql(preset_db)
        self.log.info(preset_db_res)
        self.assertIn(self.constant.CREATE_DATABASE_SUCCESS, preset_db_res,
                      f"创建兼容B库失败")

    def test_autocommit(self):
        text1 = '-----step1:连接数据库，关闭自动提交，建表;expect:建表成功-----'
        self.log.info(text1)
        sql1 = f"set autocommit=0;" \
               f"drop table if exists {self.tb_name} cascade;" \
               f"create table {self.tb_name}(" \
               f"c_int int primary key, c_float float);" \
               f"commit;" \
               f"insert into {self.tb_name} values(1, 105.5), (20, 655.45);" \
               f"select * from {self.tb_name} order by c_int;" \
               f"select pg_sleep(10);"
        session1 = ComThread(self.pri_sh.execut_db_sql,
                             args=(sql1, '', self.db_name))
        session1.setDaemon(True)
        session1.start()
        time.sleep(2)

        text2 = '-----step2:新开session2重启数据库;expect:重启成功-----'
        self.log.info(text2)
        session2 = ComThread(self.pri_sh.restart_db_cluster, args=())
        session2.setDaemon(True)
        session2.start()
        session1.join(30)
        session2.join(30)
        result1 = session1.get_result()
        self.log.info(f'session1_results: {result1}')
        result2 = session2.get_result()
        self.log.info(f'session2_results: {result2}')
        self.assertIn('SET', result1, f"关闭自动提交失败: {text1}")
        self.assertIn(self.constant.CREATE_TABLE_SUCCESS, result1,
                      f"建表失败: {text1}")
        self.assertIn(self.constant.COMMIT_SUCCESS_MSG, result1,
                      f"提交事务失败: {text1}")
        self.assertIn(self.constant.INSERT_SUCCESS_MSG, result1,
                      f"表中插入数据失败: {text1}")
        self.assertIn('2 rows', result1, f"执行失败: {text1}")
        self.assertTrue(result2, f"执行失败: {text2}")

        text3 = '-----step3:查询表数据;expect:表存在，无数据-----'
        self.log.info(text3)
        select_res = self.pri_sh.execut_db_sql(
            f"select * from {self.tb_name};", dbname=self.db_name)
        self.log.info(select_res)
        self.assertIn('0 rows', select_res, f"执行失败{text3}")

    def tearDown(self):
        text4 = '-----step4:清理环境 expect:成功-----'
        self.log.info(text4)
        drop_db_res = self.pri_sh.execut_db_sql(
            f"drop database if exists {self.db_name};")
        self.log.info(drop_db_res)
        self.assertIn(self.constant.DROP_DATABASE_SUCCESS, drop_db_res,
                      f"执行失败: {text4}")
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
